import { api } from '@/utils/request';

const state = {
  userInfo: uni.getStorageSync('userInfo') || null,
  token: uni.getStorageSync('token') || '',
};

const mutations = {
  SET_USER_INFO(state, userInfo) {
    state.userInfo = userInfo;
    uni.setStorageSync('userInfo', userInfo);
  },
  SET_TOKEN(state, token) {
    state.token = token;
    uni.setStorageSync('token', token);
  },
  CLEAR_USER_INFO(state) {
    state.userInfo = null;
    state.token = '';
    uni.removeStorageSync('userInfo');
    uni.removeStorageSync('token');
  },
};

const actions = {
  // 账号密码登录
  async accountLogin({ commit }, { username, password }) {
    try {
      const response = await api.post('/auth/login', { username, password });
      if (response.code === 200 && response.data.token) {
        const { user, token } = response.data;
        commit('SET_USER_INFO', user);
        commit('SET_TOKEN', token);
        return user;
      } else {
        throw new Error(response.message || '登录失败');
      }
    } catch (error) {
      console.error('账号密码登录失败:', error);
      throw error;
    }
  },

  // 注册
  async register({ commit }, registerData) {
    try {
      const response = await api.post('/auth/register', registerData);
      if (response.code === 200 && response.data.token) {
        const { user, token } = response.data;
        commit('SET_USER_INFO', user);
        commit('SET_TOKEN', token);
        return user;
      } else {
        throw new Error(response.message || '注册失败');
      }
    } catch (error) {
      console.error('注册失败:', error);
      throw error;
    }
  },

  // 更新用户信息
  async updateUserInfo({ commit }, userData) {
    try {
      const response = await api.put('/user/me', userData);
      if (response.code === 200) {
        commit('SET_USER_INFO', response.data);
        return response.data;
      } else {
        throw new Error(response.message || '更新失败');
      }
    } catch (error) {
      console.error('更新用户信息失败:', error);
      throw error;
    }
  },
  
  // 从本地存储加载用户信息
  loadUserInfo({ commit }) {
    const userInfo = uni.getStorageSync('userInfo');
    const token = uni.getStorageSync('token');
    if (userInfo && token) {
      commit('SET_USER_INFO', userInfo);
      commit('SET_TOKEN', token);
    } else {
      // 如果本地没有用户信息，可以抛出错误或静默失败
      // throw new Error('No user info found in storage');
    }
  },

  // 获取用户统计
  async getUserStats({ state }) {
    try {
      const response = await api.get(`/auth/users/stats`);
      return response.data;
    } catch (error) {
      console.error('获取用户统计失败:', error);
      return null;
    }
  },
  
  // 退出登录
  logout({ commit }) {
    commit('CLEAR_USER_INFO');
  }
};

const getters = {
  userInfo: state => state.userInfo,
  token: state => state.token,
  isLogin: state => !!state.token,
  familyId: state => state.userInfo?.familyId,
  isAdmin: state => state.userInfo?.role === 'admin'
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
}; 
